package JAVA300.第十二章网络编程;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 发送线程
 * 加属性 加构造器
 */

public class web04_UDP6_ChatThreadSend implements Runnable{

    private DatagramSocket client;
    private BufferedReader reader;

    private String toIp;
    private int toPort;


    public web04_UDP6_ChatThreadSend(int port, String toIp, int toPort) {
        try {
            this.client  = new DatagramSocket(port);
            reader = new BufferedReader(new InputStreamReader(System.in));
            this.toIp = toIp;
            this.toPort = toPort;
        } catch (SocketException e) {
            e.printStackTrace();
        }
        ;
    }

    @Override
    public void run() {
        while (true){
            String msg = null;
            try {
                msg = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] datas = msg.getBytes();


            //3封装成DatagramPacket包裹，指定目的地,最后的参数InetSocketAddress 封装ip地址和端口，也就是Server端的那个
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length,
                    new InetSocketAddress(this.toIp,this.toPort));
            //4发送包裹 send（DatagramPacket p）
            try {
                client.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (msg.equals("bye")){
                break;
            }
        }

        client.close();

    }
}
